import pygame
import math
import os
from typing import Dict, Any, List, Optional, Tuple
from .card_display import CardDisplay


class GameRenderer:
    """游戏渲染器"""
    
    def __init__(self, screen_width: int = 1600, screen_height: int = 900):
        # 设计分辨率（虚拟分辨率）
        self.design_width = screen_width
        self.design_height = screen_height
        
        # 初始化Pygame
        pygame.init()
        
        # 获取显示器实际分辨率
        display_info = pygame.display.Info()
        max_width = display_info.current_w
        max_height = display_info.current_h
        
        # 计算合适的窗口大小（留出任务栏空间）
        available_width = max_width - 100
        available_height = max_height - 100
        
        # 计算缩放比例（保持纵横比）
        scale_x = available_width / self.design_width
        scale_y = available_height / self.design_height
        self.scale = min(scale_x, scale_y, 1.0)  # 不放大，只缩小
        
        # 实际窗口大小
        self.screen_width = int(self.design_width * self.scale)
        self.screen_height = int(self.design_height * self.scale)
        
        # 创建实际窗口
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
        pygame.display.set_caption("LOCA2")
        
        # 创建虚拟surface（按设计分辨率绘制）
        self.virtual_surface = pygame.Surface((self.design_width, self.design_height))
        
        print(f"Display: {max_width}x{max_height}, Window: {self.screen_width}x{self.screen_height}, Scale: {self.scale:.2f}")
        
        # 字体
        pygame.font.init()
        self.title_font = pygame.font.Font(None, 36)
        self.normal_font = pygame.font.Font(None, 24)
        self.small_font = pygame.font.Font(None, 18)
        
        # 颜色
        self.colors = {
            'white': (255, 255, 255),
            'black': (0, 0, 0),
            'red': (255, 0, 0),
            'green': (0, 255, 0),
            'blue': (0, 0, 255),
            'yellow': (255, 255, 0),
            'gray': (128, 128, 128),
            'dark_gray': (64, 64, 64),
            'light_gray': (192, 192, 192),
            'brown': (139, 69, 19),
            'purple': (128, 0, 128),
            'orange': (255, 165, 0)
        }
        
        # 卡牌显示器（使用设计分辨率）
        self.card_display = CardDisplay(self.design_width, self.design_height)
        
        # 背景图片
        self.background_image = None
        self._load_background()
        
        # 布局参数
        self.card_width = 100  # 减小卡牌宽度（原120）
        self.card_height = 140  # 减小卡牌高度（原160）
        self.card_spacing = 8  # 稍微减小间距（原10）
        self.margin = 20
        
        # 区域定义（使用设计分辨率）
        self.opponent_area = pygame.Rect(0, 0, self.design_width, self.design_height // 2)
        self.player_area = pygame.Rect(0, self.design_height // 2, self.design_width, self.design_height // 2)
    
    def _load_background(self):
        """加载背景图片"""
        try:
            # 尝试多种可能的路径
            possible_paths = [
                # 当通过start_client.py启动时（工作目录是项目根目录）
                "client/assets/background/background.jpg",
                # 当直接运行main.py时（工作目录是client目录）
                "assets/background/background.jpg",
                # 相对于当前文件的路径
                os.path.join(os.path.dirname(os.path.dirname(__file__)), "assets", "background", "background.jpg"),
                # 相对于项目根目录的路径
                os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "client", "assets", "background", "background.jpg")
            ]
            
            background_path = None
            for path in possible_paths:
                if os.path.exists(path):
                    background_path = path
                    break
            
            if background_path:
                self.background_image = pygame.image.load(background_path)
                # 缩放背景图片以适应设计分辨率
                self.background_image = pygame.transform.scale(self.background_image, (self.design_width, self.design_height))
                print(f"Background loaded successfully: {background_path}")
            else:
                print(f"Background image not found. Tried paths: {possible_paths}")
                self.background_image = None
        except pygame.error as e:
            print(f"Failed to load background image: {e}")
            self.background_image = None
        
        # 状态
        self.selected_card = None
        self.highlighted_targets = []
        self.show_tooltip = False
        self.tooltip_card = None
        self.tooltip_pos = (0, 0)
    
    def render_game(self, game_state: Optional[Dict[str, Any]], player_id: str, selected_cards: List[str] = None,
                    interaction_state: str = None, valid_targets: List = None, selected_target: str = None,
                    pending_card_name: str = None, available_decks: List = None):
        """渲染游戏画面（包含flip）"""
        self.render_game_without_flip(game_state, player_id, selected_cards, interaction_state, valid_targets, selected_target, pending_card_name, available_decks)
        self._scale_and_display()
        pygame.display.flip()
    
    def render_game_without_flip(self, game_state: Optional[Dict[str, Any]], player_id: str, selected_cards: List[str] = None,
                    interaction_state: str = None, valid_targets: List = None, selected_target: str = None,
                    pending_card_name: str = None, available_decks: List = None):
        """渲染游戏画面（不包含flip，用于后续在上面绘制UI元素）"""
        # 在虚拟surface上绘制
        # 绘制背景
        if self.background_image:
            self.virtual_surface.blit(self.background_image, (0, 0))
        else:
            self.virtual_surface.fill(self.colors['light_gray'])
        
        if not game_state:
            self._render_waiting_screen()
            return
        
        game_phase = game_state.get("game_phase", "")
        
        if game_phase == "DECK_SELECTION":
            self._render_deck_selection_screen(game_state, player_id, available_decks or [])
        elif game_phase == "MULLIGAN":
            self._render_mulligan_screen(game_state, player_id, selected_cards or [])
        elif game_phase == "PLAYING":
            self._render_game_screen(game_state, player_id)
            
            # 渲染目标高亮
            if interaction_state == "TARGET_SELECTION" and valid_targets:
                self._render_target_highlights(valid_targets, player_id, game_state)
            
            # 渲染交互提示
            if interaction_state and interaction_state != "IDLE":
                self._render_interaction_hint(interaction_state, pending_card_name)
        elif game_phase == "ENDED":
            self._render_game_over_screen(game_state, player_id)
        
        # 渲染提示框
        if self.show_tooltip and self.tooltip_card:
            self.card_display.draw_card_tooltip(self.virtual_surface, self.tooltip_card, 
                                              self.tooltip_pos[0], self.tooltip_pos[1])
        
        # 渲染动画中的卡牌和效果
        self._render_animations()
    
    def _scale_and_display(self):
        """将虚拟surface缩放并显示到实际窗口"""
        if self.scale < 1.0:
            # 需要缩放
            scaled_surface = pygame.transform.smoothscale(
                self.virtual_surface, 
                (self.screen_width, self.screen_height)
            )
            self.screen.blit(scaled_surface, (0, 0))
        else:
            # 不需要缩放，直接显示
            self.screen.blit(self.virtual_surface, (0, 0))
    
    def scale_mouse_pos(self, pos: Tuple[int, int]) -> Tuple[int, int]:
        """将实际鼠标位置转换为虚拟分辨率下的位置"""
        if self.scale < 1.0:
            return (int(pos[0] / self.scale), int(pos[1] / self.scale))
        return pos
    
    def _render_waiting_screen(self):
        """渲染等待画面"""
        text = self.title_font.render("Waiting for connection...", True, self.colors['black'])
        text_rect = text.get_rect(center=(self.design_width // 2, self.design_height // 2))
        self.virtual_surface.blit(text, text_rect)
    
    def _render_deck_selection_screen(self, game_state: Dict[str, Any], player_id: str, available_decks: List = None):
        """渲染卡组选择画面"""
        if available_decks is None:
            available_decks = []
        
        # 检查玩家是否已选择卡组
        deck_selection_completed = game_state.get("deck_selection_completed", False)
        
        if deck_selection_completed:
            # 玩家已选择，显示等待画面
            title_text = self.title_font.render("Deck Selected", True, self.colors['green'])
            title_rect = title_text.get_rect(center=(self.design_width // 2, self.design_height // 2 - 40))
            self.virtual_surface.blit(title_text, title_rect)
            
            # 显示选择的卡组
            selected_deck_name = game_state.get("deck_selected", "Unknown")
            deck_text = self.normal_font.render(f"Your deck: {selected_deck_name}", True, self.colors['black'])
            deck_rect = deck_text.get_rect(center=(self.design_width // 2, self.design_height // 2))
            self.virtual_surface.blit(deck_text, deck_rect)
            
            # 等待提示
            waiting_text = self.title_font.render("Waiting for opponent to select deck...", True, self.colors['black'])
            waiting_rect = waiting_text.get_rect(center=(self.design_width // 2, self.design_height // 2 + 60))
            self.virtual_surface.blit(waiting_text, waiting_rect)
        else:
            # 玩家未选择，显示卡组列表
            title_text = self.title_font.render("Select Your Deck", True, self.colors['black'])
            title_rect = title_text.get_rect(center=(self.design_width // 2, 80))
            self.virtual_surface.blit(title_text, title_rect)
            
            # 渲染卡组按钮
            button_width = 400
            button_height = 80
            start_y = 150
            button_spacing = 20
            
            for i, deck in enumerate(available_decks):
                button_x = self.design_width // 2 - button_width // 2
                button_y = start_y + i * (button_height + button_spacing)
                
                # 绘制按钮背景
                button_rect = pygame.Rect(button_x, button_y, button_width, button_height)
                pygame.draw.rect(self.virtual_surface, self.colors['white'], button_rect)
                pygame.draw.rect(self.virtual_surface, self.colors['black'], button_rect, 3)
                
                # 绘制卡组标题
                deck_title = deck.get("title", "Unknown Deck")
                title_text = self.normal_font.render(deck_title, True, self.colors['black'])
                title_text_rect = title_text.get_rect(center=(button_x + button_width // 2, button_y + 25))
                self.virtual_surface.blit(title_text, title_text_rect)
                
                # 绘制卡组描述
                deck_desc = deck.get("description", "")
                if len(deck_desc) > 60:
                    deck_desc = deck_desc[:60] + "..."
                desc_text = self.small_font.render(deck_desc, True, self.colors['dark_gray'])
                desc_text_rect = desc_text.get_rect(center=(button_x + button_width // 2, button_y + 50))
                self.virtual_surface.blit(desc_text, desc_text_rect)
    
    def _render_mulligan_screen(self, game_state: Dict[str, Any], player_id: str, selected_cards: List[str] = None):
        """渲染换牌画面"""
        if selected_cards is None:
            selected_cards = []
        
        # 检查当前玩家是否已完成换牌
        mulligan_completed = game_state.get("mulligan_completed", False)
        
        if mulligan_completed:
            # 玩家已完成换牌，显示等待画面
            title_text = self.title_font.render("Mulligan Complete", True, self.colors['green'])
            title_rect = title_text.get_rect(center=(self.design_width // 2, self.design_height // 2 - 40))
            self.virtual_surface.blit(title_text, title_rect)
            
            waiting_text = self.title_font.render("Waiting for opponent to mulligan...", True, self.colors['black'])
            waiting_rect = waiting_text.get_rect(center=(self.design_width // 2, self.design_height // 2 + 20))
            self.virtual_surface.blit(waiting_text, waiting_rect)
        else:
            # 玩家未完成换牌，显示选牌界面
            # 标题
            title_text = self.title_font.render("Select 4 cards to return", True, self.colors['black'])
            title_rect = title_text.get_rect(center=(self.design_width // 2, 50))
            self.virtual_surface.blit(title_text, title_rect)
            
            # 显示选中的卡牌数量
            count_text = self.normal_font.render(f"Selected: {len(selected_cards)}/4", True, self.colors['black'])
            count_rect = count_text.get_rect(center=(self.design_width // 2, 80))
            self.virtual_surface.blit(count_text, count_rect)
            
            # 显示换牌卡牌（居中显示）
            mulligan_cards = game_state.get("mulligan_cards", [])
            if mulligan_cards:
                # 计算卡牌列表的总宽度并居中
                card_width = self.card_width
                card_spacing = self.card_spacing
                total_width = len(mulligan_cards) * card_width + (len(mulligan_cards) - 1) * card_spacing
                start_x = self.design_width // 2 - total_width // 2
                self._render_card_list(mulligan_cards, start_x, 100, "mulligan", selected_cards)
            
            # 确认按钮
            confirm_rect = pygame.Rect(self.design_width // 2 - 60, self.design_height - 100, 120, 40)
            pygame.draw.rect(self.virtual_surface, self.colors['green'], confirm_rect)
            pygame.draw.rect(self.virtual_surface, self.colors['black'], confirm_rect, 2)
            
            confirm_text = self.normal_font.render("Confirm", True, self.colors['white'])
            confirm_text_rect = confirm_text.get_rect(center=confirm_rect.center)
            self.virtual_surface.blit(confirm_text, confirm_text_rect)
    
    def _render_game_screen(self, game_state: Dict[str, Any], player_id: str):
        """渲染游戏画面"""
        players = game_state.get("players", {})
        current_player = game_state.get("current_player", "")
        is_my_turn = current_player == player_id
        
        # 获取玩家和对手数据
        my_data = players.get(player_id, {})
        opponent_id = self._get_opponent_id(player_id, players)
        opponent_data = players.get(opponent_id, {})
        
        # 渲染对手区域
        self._render_player_area(opponent_data, self.opponent_area, is_opponent=True, game_state=game_state, player_id=player_id)
        
        # 渲染我的区域
        self._render_player_area(my_data, self.player_area, is_opponent=False, game_state=game_state, player_id=player_id)
        
        # 渲染回合信息
        self._render_turn_info(game_state, player_id)
        
        # 渲染结束回合按钮
        if is_my_turn:
            self._render_end_turn_button()
    
    def _render_player_area(self, player_data: Dict[str, Any], area: pygame.Rect, is_opponent: bool, game_state: Dict[str, Any] = None, player_id: str = None):
        """渲染玩家区域"""
        # 召唤师
        summoner = player_data.get("summoner", {})
        self._render_summoner(summoner, area, is_opponent)
        
        # 场地
        battlefield = player_data.get("battlefield", [])
        self._render_battlefield(battlefield, area, is_opponent, game_state, player_id)
        
        # 手牌（只显示自己的）
        if not is_opponent:
            hand = player_data.get("hand", [])
            self._render_hand(hand, area)
        
        # 牌堆信息
        self._render_pile_info(player_data, area, is_opponent)
    
    def _render_summoner(self, summoner: Dict[str, Any], area: pygame.Rect, is_opponent: bool):
        """渲染召唤师"""
        if not summoner:
            return
        
        # 补充卡牌数据（从card_registry获取完整信息）
        card_id = summoner.get("card_id", "")
        if card_id and card_id in self.card_display.card_registry:
            # 合并注册表数据和服务器数据
            registry_data = self.card_display.card_registry[card_id].copy()
            registry_data.update(summoner)  # 服务器数据覆盖注册表数据
            summoner_data = registry_data
        else:
            summoner_data = summoner
        
        # 召唤师位置
        summoner_x = self.design_width // 2 - self.card_width // 2
        center_line = self.design_height // 2
        
        if is_opponent:
            # 对手召唤师在中线上方，场地后方（向上）- 保持对称
            summoner_y = center_line - 100 - self.card_height - 40 - self.card_height
        else:
            # 我的召唤师上移150px，为手牌留出空间（不对称）
            summoner_y = center_line + 100 + self.card_height + 40 - 150
        
        # 绘制召唤师
        self.card_display.draw_card(self.virtual_surface, summoner_data, summoner_x, summoner_y)
        
        # 召唤师标签
        label = "Enemy Summoner" if is_opponent else "My Summoner"
        label_text = self.small_font.render(label, True, self.colors['black'])
        if is_opponent:
            label_rect = label_text.get_rect(center=(summoner_x + self.card_width // 2, summoner_y - 15))
        else:
            label_rect = label_text.get_rect(center=(summoner_x + self.card_width // 2, summoner_y + self.card_height + 10))
        self.virtual_surface.blit(label_text, label_rect)
    
    def _render_battlefield(self, battlefield: List[Optional[Dict[str, Any]]], area: pygame.Rect, is_opponent: bool, game_state: Dict[str, Any] = None, player_id: str = None):
        """渲染场地（动态居中显示）"""
        # 场地位置
        center_line = self.design_height // 2
        
        if is_opponent:
            # 对手场地在中线上方100px（保持对称）
            battlefield_y = center_line - 100 - self.card_height
        else:
            # 我的场地上移150px（为手牌留出更多空间）
            battlefield_y = center_line + 100 - 150
        
        # 计算场上有多少个Champion（用于居中显示）
        champions_count = sum(1 for c in battlefield if c is not None)
        
        # 计算总宽度并居中
        if champions_count > 0:
            total_width = champions_count * self.card_width + (champions_count - 1) * self.card_spacing
            start_x = self.design_width // 2 - total_width // 2
        else:
            start_x = self.design_width // 2
        
        # 渲染时跳过None，只渲染实际存在的Champion
        rendered_index = 0
        for i, champion in enumerate(battlefield):
            if champion is None:
                continue
            
            # 计算位置（使用rendered_index而不是i）
            x = start_x + rendered_index * (self.card_width + self.card_spacing)
            y = battlefield_y
            rendered_index += 1
            
            # 补充卡牌数据（从card_registry获取完整信息）
            card_id = champion.get("card_id", "")
            if card_id and card_id in self.card_display.card_registry:
                # 合并注册表数据和服务器数据
                registry_data = self.card_display.card_registry[card_id].copy()
                registry_data.update(champion)  # 服务器数据覆盖注册表数据
                champion_data = registry_data
            else:
                champion_data = champion
            
            # 检查是否高亮
            highlighted = champion_data.get("card_id") in self.highlighted_targets
            selected = champion_data.get("card_id") == self.selected_card
            
            # 绘制Champion
            self.card_display.draw_card(self.virtual_surface, champion_data, x, y, highlighted, selected)
            
            # 绘制守卫连线
            if champion_data.get("guarding_target_id"):
                self._render_guard_line(champion_data, x, y, area, is_opponent, game_state, player_id)
    
    def _render_hand(self, hand: List[Dict[str, Any]], area: pygame.Rect):
        """渲染手牌"""
        if not hand:
            return
        
        # 手牌位置 - 在最底部
        hand_y = area.bottom - self.card_height - 10
        
        # 计算手牌间距
        total_width = len(hand) * self.card_width + (len(hand) - 1) * self.card_spacing
        start_x = area.centerx - total_width // 2
        
        for i, card in enumerate(hand):
            x = start_x + i * (self.card_width + self.card_spacing)
            y = hand_y
            
            # 补充卡牌数据（从card_registry获取完整信息）
            card_id = card.get("card_id", "")
            if card_id and card_id in self.card_display.card_registry:
                # 合并注册表数据和服务器数据
                registry_data = self.card_display.card_registry[card_id].copy()
                registry_data.update(card)  # 服务器数据覆盖注册表数据
                card_data = registry_data
            else:
                card_data = card
            
            # 检查是否选中
            selected = card_data.get("card_id") == self.selected_card
            
            # 绘制卡牌
            self.card_display.draw_card(self.virtual_surface, card_data, x, y, selected=selected)
    
    def _render_pile_info(self, player_data: Dict[str, Any], area: pygame.Rect, is_opponent: bool):
        """渲染牌堆信息"""
        draw_count = player_data.get("draw_pile_count", 0)
        discard_count = player_data.get("discard_pile_count", 0)
        hand_count = player_data.get("hand_count", len(player_data.get("hand", [])))
        
        # 位置
        if is_opponent:
            x = area.left + 20
            y = area.top + 20
        else:
            x = area.left + 20
            y = area.bottom - 60
        
        # 抽牌堆
        draw_text = self.small_font.render(f"Draw: {draw_count}", True, self.colors['white'])
        self.virtual_surface.blit(draw_text, (x, y))
        
        # 弃牌堆
        discard_text = self.small_font.render(f"Discard: {discard_count}", True, self.colors['white'])
        self.virtual_surface.blit(discard_text, (x, y + 20))
        
        # 敌方手牌数（只显示对手的）
        if is_opponent:
            hand_text = self.small_font.render(f"Hand: {hand_count}", True, self.colors['white'])
            self.virtual_surface.blit(hand_text, (x, y + 40))
    
    def _render_turn_info(self, game_state: Dict[str, Any], player_id: str):
        """渲染回合信息"""
        current_player = game_state.get("current_player", "")
        turn_number = game_state.get("turn_number", 0)
        is_my_turn = current_player == player_id
        
        # 回合数
        turn_text = self.normal_font.render(f"Turn {turn_number}", True, self.colors['white'])
        self.virtual_surface.blit(turn_text, (self.design_width - 150, 20))
        
        # 当前回合玩家
        player_text = "Your Turn" if is_my_turn else "Opponent's Turn"
        color = self.colors['green'] if is_my_turn else self.colors['red']
        player_label = self.normal_font.render(player_text, True, color)
        self.virtual_surface.blit(player_label, (self.design_width - 150, 50))
        
        # PP信息
        players = game_state.get("players", {})
        my_data = players.get(player_id, {})
        current_pp = my_data.get("current_pp", 0)
        max_pp = my_data.get("max_pp", 0)
        
        pp_text = self.normal_font.render(f"PP: {current_pp}/{max_pp}", True, self.colors['white'])
        self.virtual_surface.blit(pp_text, (self.design_width - 150, 80))
    
    def _render_end_turn_button(self):
        """渲染结束回合按钮"""
        button_rect = pygame.Rect(self.design_width - 120, self.design_height - 60, 100, 40)
        pygame.draw.rect(self.virtual_surface, self.colors['orange'], button_rect)
        pygame.draw.rect(self.virtual_surface, self.colors['black'], button_rect, 2)
        
        button_text = self.normal_font.render("End Turn", True, self.colors['white'])
        button_text_rect = button_text.get_rect(center=button_rect.center)
        self.virtual_surface.blit(button_text, button_text_rect)
    
    def _render_guard_line(self, guard: Dict[str, Any], x: int, y: int, area: pygame.Rect, is_opponent: bool, game_state: Dict[str, Any] = None, player_id: str = None):
        """绘制守卫关系标识（简化版 - 黄色高亮）"""
        guarding_target_id = guard.get("guarding_target_id")
        if not guarding_target_id:
            return
        
        target_pos = self._get_guard_target_position(guarding_target_id, is_opponent, game_state, player_id)
        if not target_pos:
            return
        
        # 守护者黄色边框（醒目）
        guard_rect = pygame.Rect(x - 3, y - 3, self.card_width + 6, self.card_height + 6)
        pygame.draw.rect(self.virtual_surface, self.colors['yellow'], guard_rect, 4)
        
        # 守护者盾牌图标（右上角）
        shield_icon_size = 28
        shield_surface = pygame.Surface((shield_icon_size, shield_icon_size), pygame.SRCALPHA)
        pygame.draw.rect(shield_surface, (255, 215, 0), (6, 4, 16, 14))
        pygame.draw.polygon(shield_surface, (255, 215, 0), [(14, 18), (8, 24), (20, 24)])
        self.virtual_surface.blit(shield_surface, (x + self.card_width - 32, y + 4))
        
        # 被守护者黄色边框
        target_x = target_pos[0] - self.card_width // 2
        target_y = target_pos[1] - self.card_height // 2
        target_rect = pygame.Rect(target_x - 3, target_y - 3, self.card_width + 6, self.card_height + 6)
        pygame.draw.rect(self.virtual_surface, self.colors['yellow'], target_rect, 4)
        
        # 半透明黄色连线
        guard_center = (x + self.card_width // 2, y + self.card_height // 2)
        pygame.draw.line(self.virtual_surface, (*self.colors['yellow'], 128), 
                         guard_center, target_pos, 2)
    
    def _get_guard_target_position(self, target_id: str, is_opponent: bool, game_state: Dict[str, Any] = None, player_id: str = None) -> Optional[Tuple[int, int]]:
        """获取被守护目标的位置"""
        if target_id.endswith("_summoner"):
            # 召唤师位置
            summoner_x = self.design_width // 2 - self.card_width // 2
            center_line = self.design_height // 2
            
            if is_opponent:
                # 对手召唤师
                summoner_y = center_line - 100 - self.card_height - 40 - self.card_height
            else:
                # 己方召唤师
                summoner_y = center_line + 100 + self.card_height + 40 - 150
            
            return (summoner_x + self.card_width // 2, summoner_y + self.card_height // 2)
        else:
            # 场上单位位置
            return self._get_champion_center_position(target_id, is_opponent, game_state, player_id)
    
    def _get_champion_center_position(self, champion_id: str, is_opponent: bool, game_state: Dict[str, Any] = None, player_id: str = None) -> Optional[Tuple[int, int]]:
        """获取场上单位的中心位置"""
        # 使用传递的游戏状态
        if not game_state or not player_id:
            return None
        
        center_line = self.design_height // 2
        
        if is_opponent:
            battlefield_y = center_line - 100 - self.card_height
            player_key = 'opponent'
        else:
            battlefield_y = center_line + 100 - 150
            player_key = 'player'
        
        # 获取对应玩家的战场数据
        players = game_state.get("players", {})
        battlefield = []
        
        # 找到对应的玩家ID
        for pid, player_data in players.items():
            if player_key == 'opponent' and pid != player_id:
                battlefield = player_data.get("battlefield", [])
                break
            elif player_key == 'player' and pid == player_id:
                battlefield = player_data.get("battlefield", [])
                break
        
        # 计算实际存在的champion数量（用于居中）
        champions_count = sum(1 for c in battlefield if c is not None)
        
        if champions_count == 0:
            return None
        
        # 计算该champion在渲染中的实际索引
        total_width = champions_count * self.card_width + (champions_count - 1) * self.card_spacing
        start_x = self.design_width // 2 - total_width // 2
        
        rendered_index = 0
        for champion in battlefield:
            if champion is not None:
                # 检查是否为目标champion
                if (champion.get("instance_id") == champion_id or 
                    champion.get("card_id") == champion_id):
                    card_x = start_x + rendered_index * (self.card_width + self.card_spacing)
                    card_y = battlefield_y
                    # 返回中心位置
                    return (card_x + self.card_width // 2, card_y + self.card_height // 2)
                rendered_index += 1
        
        return None
    
    def _draw_arrow(self, start_pos: Tuple[int, int], end_pos: Tuple[int, int], color: Tuple[int, int, int]):
        """绘制箭头"""
        # 计算箭头方向
        dx = end_pos[0] - start_pos[0]
        dy = end_pos[1] - start_pos[1]
        length = math.sqrt(dx * dx + dy * dy)
        
        if length == 0:
            return
        
        # 箭头大小
        arrow_size = 10
        angle = math.atan2(dy, dx)
        
        # 箭头顶点
        arrow_x1 = end_pos[0] - arrow_size * math.cos(angle - math.pi / 6)
        arrow_y1 = end_pos[1] - arrow_size * math.sin(angle - math.pi / 6)
        arrow_x2 = end_pos[0] - arrow_size * math.cos(angle + math.pi / 6)
        arrow_y2 = end_pos[1] - arrow_size * math.sin(angle + math.pi / 6)
        
        # 绘制箭头
        pygame.draw.polygon(self.virtual_surface, color, [
            end_pos,
            (arrow_x1, arrow_y1),
            (arrow_x2, arrow_y2)
        ])
    
    def _render_game_over_screen(self, game_state: Dict[str, Any], player_id: str):
        """渲染游戏结束画面"""
        # 这里可以显示游戏结果
        text = self.title_font.render("Game Over", True, self.colors['white'])
        text_rect = text.get_rect(center=(self.design_width // 2, self.design_height // 2))
        self.virtual_surface.blit(text, text_rect)
    
    def _get_opponent_id(self, player_id: str, players: Dict[str, Any]) -> str:
        """获取对手ID"""
        for pid in players.keys():
            if pid != player_id:
                return pid
        return ""
    
    def _render_card_list(self, cards: List[Any], x: int, y: int, card_type: str, selected_cards: List[int] = None):
        """渲染卡牌列表"""
        if selected_cards is None:
            selected_cards = []
            
        for i, card in enumerate(cards):
            card_x = x + i * (self.card_width + self.card_spacing)
            card_y = y
            
            # 如果card是字符串（卡牌ID），需要转换为卡牌对象
            if isinstance(card, str):
                # 从卡牌注册表获取卡牌信息
                card_data = self.card_display.card_registry.get(card, {})
                if not card_data:
                    continue
                # 添加card_id字段
                card_data = card_data.copy()
                card_data["card_id"] = card
            else:
                card_data = card
            
            # 检查是否选中 - 支持多种格式
            selected = False
            if isinstance(selected_cards, list) and len(selected_cards) > 0:
                # 支持元组格式 [(idx, card_id), ...]
                if isinstance(selected_cards[0], tuple):
                    selected = any(idx == i for idx, _ in selected_cards)
                # 支持纯索引格式 [0, 2, 3]
                else:
                    selected = i in selected_cards
            
            # 绘制卡牌
            self.card_display.draw_card(self.virtual_surface, card_data, card_x, card_y, selected=selected)
    
    def handle_mouse_click(self, pos: Tuple[int, int], game_state: Optional[Dict[str, Any]], player_id: str) -> Optional[Dict[str, Any]]:
        """处理鼠标点击"""
        if not game_state:
            return None
        
        game_phase = game_state.get("game_phase", "")
        
        if game_phase == "MULLIGAN":
            return self._handle_mulligan_click(pos, game_state)
        elif game_phase == "PLAYING":
            return self._handle_game_click(pos, game_state, player_id)
        
        return None
    
    def _handle_mulligan_click(self, pos: Tuple[int, int], game_state: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """处理换牌阶段的点击"""
        mulligan_cards = game_state.get("mulligan_cards", [])
        
        # 检查是否点击了卡牌
        for i, card in enumerate(mulligan_cards):
            card_x = 100 + i * (self.card_width + self.card_spacing)
            card_y = 100
            card_rect = pygame.Rect(card_x, card_y, self.card_width, self.card_height)
            
            if card_rect.collidepoint(pos):
                # 获取卡牌ID（card可能是字符串或字典）
                card_id = card if isinstance(card, str) else card.get("card_id")
                
                # 切换选中状态
                if self.selected_card == card_id:
                    self.selected_card = None
                else:
                    self.selected_card = card_id
                return {"action": "select_card", "card_id": card_id}
        
        # 检查确认按钮
        confirm_rect = pygame.Rect(self.design_width // 2 - 60, self.design_height - 100, 120, 40)
        if confirm_rect.collidepoint(pos):
            return {"action": "confirm_mulligan"}
        
        return None
    
    def _handle_game_click(self, pos: Tuple[int, int], game_state: Dict[str, Any], player_id: str) -> Optional[Dict[str, Any]]:
        """处理游戏阶段的点击"""
        # 检查结束回合按钮
        button_rect = pygame.Rect(self.design_width - 120, self.design_height - 60, 100, 40)
        if button_rect.collidepoint(pos):
            return {"action": "end_turn"}
        
        # 检查手牌点击
        players = game_state.get("players", {})
        my_data = players.get(player_id, {})
        hand = my_data.get("hand", [])
        
        hand_y = self.design_height // 2 + self.design_height // 2 - self.card_height - 20
        total_width = len(hand) * self.card_width + (len(hand) - 1) * self.card_spacing
        start_x = self.design_width // 2 - total_width // 2
        
        for i, card in enumerate(hand):
            card_x = start_x + i * (self.card_width + self.card_spacing)
            card_y = hand_y
            card_rect = pygame.Rect(card_x, card_y, self.card_width, self.card_height)
            
            if card_rect.collidepoint(pos):
                return {"action": "select_card", "card_id": card.get("card_id")}
        
        # 检查场地点击
        battlefield = my_data.get("battlefield", [])
        battlefield_y = self.design_height // 2 + self.design_height // 2 - self.card_height // 2
        
        for i, champion in enumerate(battlefield):
            if champion is None:
                continue
            
            card_x = self.margin + i * (self.card_width + self.card_spacing)
            card_y = battlefield_y
            card_rect = pygame.Rect(card_x, card_y, self.card_width, self.card_height)
            
            if card_rect.collidepoint(pos):
                return {"action": "select_champion", "champion_id": champion.get("card_id")}
        
        return None
    
    def set_selected_card(self, card_id: Optional[str]):
        """设置选中的卡牌"""
        self.selected_card = card_id
    
    def set_highlighted_targets(self, targets: List[str]):
        """设置高亮目标"""
        self.highlighted_targets = targets
    
    def show_card_tooltip(self, card: Optional[Dict[str, Any]], pos: Tuple[int, int]):
        """显示卡牌提示框"""
        self.tooltip_card = card
        self.tooltip_pos = pos
        self.show_tooltip = card is not None
    
    def hide_tooltip(self):
        """隐藏提示框"""
        self.show_tooltip = False
        self.tooltip_card = None
    
    def _render_target_highlights(self, valid_targets: List, player_id: str, game_state: Dict[str, Any]):
        """高亮显示可选择的目标"""
        players = game_state.get("players", {})
        
        for target in valid_targets:
            target_id = target["id"]
            target_type = target["type"]
            
            # 找到目标的渲染位置（使用与渲染器相同的计算）
            summoner_x = self.design_width // 2 - self.card_width // 2
            center_line = self.design_height // 2
            
            if target_type == "summoner":
                # 高亮召唤师
                if target_id == f"{player_id}_summoner":
                    # 己方召唤师（上移150px为手牌留空间）
                    summoner_y = center_line + 100 + self.card_height + 40 - 150
                else:
                    # 对手召唤师（保持对称位置）
                    summoner_y = center_line - 100 - self.card_height - 40 - self.card_height
                
                # 绘制高亮边框
                highlight_rect = pygame.Rect(summoner_x - 5, summoner_y - 5, self.card_width + 10, self.card_height + 10)
                pygame.draw.rect(self.virtual_surface, self.colors['green'], highlight_rect, 3)
            
            elif target_type == "champion":
                # 高亮场上单位（动态居中）
                my_battlefield = players.get(player_id, {}).get("battlefield", [])
                opponent_id = None
                for pid in players.keys():
                    if pid != player_id:
                        opponent_id = pid
                        break
                opponent_battlefield = players.get(opponent_id, {}).get("battlefield", []) if opponent_id else []
                
                # 使用与渲染相同的位置计算
                center_line = self.design_height // 2
                
                # 检查己方场地（动态居中，上移150px）
                my_battlefield_y = center_line + 100 - 150
                my_champions = [c for c in my_battlefield if c is not None]
                if my_champions:
                    my_total_width = len(my_champions) * self.card_width + (len(my_champions) - 1) * self.card_spacing
                    my_start_x = self.design_width // 2 - my_total_width // 2
                    
                    rendered_index = 0
                    for champion in my_champions:
                        if champion.get("instance_id") == target_id or champion.get("card_id") == target_id:
                            card_x = my_start_x + rendered_index * (self.card_width + self.card_spacing)
                            card_y = my_battlefield_y
                            highlight_rect = pygame.Rect(card_x - 5, card_y - 5, self.card_width + 10, self.card_height + 10)
                            pygame.draw.rect(self.virtual_surface, self.colors['green'], highlight_rect, 3)
                            break
                        rendered_index += 1
                
                # 检查对手场地（动态居中，镜像对称）
                opponent_battlefield_y = center_line - 100 - self.card_height
                opponent_champions = [c for c in opponent_battlefield if c is not None]
                if opponent_champions:
                    opponent_total_width = len(opponent_champions) * self.card_width + (len(opponent_champions) - 1) * self.card_spacing
                    opponent_start_x = self.design_width // 2 - opponent_total_width // 2

                    rendered_index = 0
                    for champion in opponent_champions:
                        if champion.get("instance_id") == target_id or champion.get("card_id") == target_id:
                            card_x = opponent_start_x + rendered_index * (self.card_width + self.card_spacing)
                            card_y = opponent_battlefield_y
                            highlight_rect = pygame.Rect(card_x - 5, card_y - 5, self.card_width + 10, self.card_height + 10)
                            pygame.draw.rect(self.virtual_surface, self.colors['green'], highlight_rect, 3)
                            break
                        rendered_index += 1
    def _render_interaction_hint(self, interaction_state: str, card_name: str = None):
        """Render interaction state hint"""
        hint_text = ""
        if interaction_state == "CARD_SELECTED":
            hint_text = f"Selected: {card_name or 'Unknown Card'} - Click Confirm or Cancel"
        elif interaction_state == "TARGET_SELECTION":
            hint_text = f"Select a target for {card_name or 'card'}"
        
        if hint_text:
            # 在屏幕顶部中央渲染黄色提示文本
            text = self.title_font.render(hint_text, True, self.colors['yellow'])
            bg = pygame.Surface((text.get_width() + 40, text.get_height() + 20))
            bg.fill(self.colors['black'])
            bg.set_alpha(200)
            bg_rect = bg.get_rect(center=(self.design_width // 2, 50))
            text_rect = text.get_rect(center=(self.design_width // 2, 50))
            self.virtual_surface.blit(bg, bg_rect)
            self.virtual_surface.blit(text, text_rect)
    
    def _render_animations(self):
        """渲染动画中的卡牌和效果"""
        # 这个方法需要从主游戏类传递动画管理器
        # 暂时为空实现
        pass
    
    def render_animated_card(self, card_data: Dict[str, Any], pos: Tuple[int, int], 
                           scale: float = 1.0, alpha: int = 255):
        """渲染动画中的卡牌"""
        # 创建临时surface用于缩放和透明度
        temp_surface = pygame.Surface((self.card_width, self.card_height), pygame.SRCALPHA)
        
        # 绘制卡牌到临时surface
        self.card_display.draw_card(temp_surface, card_data, 0, 0)
        
        # 如果需要缩放
        if scale != 1.0:
            new_width = int(self.card_width * scale)
            new_height = int(self.card_height * scale)
            temp_surface = pygame.transform.scale(temp_surface, (new_width, new_height))
        
        # 设置透明度（如果有alpha通道）
        if alpha < 255:
            temp_surface.set_alpha(alpha)
        
        # 绘制到主surface
        self.virtual_surface.blit(temp_surface, pos)
    
    def render_damage_number(self, damage: int, pos: Tuple[int, int], alpha: int = 255):
        """渲染伤害数字"""
        damage_text = self.title_font.render(f"-{damage}", True, self.colors['red'])
        
        # 设置透明度
        damage_surface = damage_text.copy()
        damage_surface.set_alpha(alpha)
        
        # 绘制到主surface
        self.virtual_surface.blit(damage_surface, pos)
    
    def render_attack_indicator(self, pos: Tuple[int, int], alpha: int = 255):
        """渲染攻击指示器（攻击者的迷你表示）"""
        # 绘制一个红色边框的小矩形表示攻击者
        indicator_size = 30
        
        # 创建临时surface
        indicator_surface = pygame.Surface((indicator_size, indicator_size), pygame.SRCALPHA)
        
        # 绘制红色边框矩形
        pygame.draw.rect(indicator_surface, (*self.colors['red'], alpha), 
                        (0, 0, indicator_size, indicator_size), 3)
        
        # 绘制攻击箭头图标
        arrow_points = [(indicator_size // 2, 5), 
                       (indicator_size - 5, indicator_size // 2),
                       (indicator_size // 2, indicator_size - 5)]
        pygame.draw.polygon(indicator_surface, (*self.colors['red'], alpha), arrow_points)
        
        # 绘制到主surface（居中对齐）
        self.virtual_surface.blit(indicator_surface, 
                                 (pos[0] - indicator_size // 2, pos[1] - indicator_size // 2))
